// pages/post5/post5.js
const app = getApp(), core = require('../../utils/core'), util = require('../../utils/util'), WeValidator = require('../../utils/we-validator');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    job: {locations:[]},
    areas: [],
    addressList:[],
    selectedDistrict: null,
    index:null,
  },
  changetab(e){
    let index = e.currentTarget.dataset.index;
    let addressList = this.data.addressList;
    for(let i=0;i<addressList.length;i++){
      addressList[i].checked = false
    }
    addressList[index].checked = true;
    this.setData({
      addressList: addressList
    })
  },

  onLoad: function (options) {
    this.getOpenerEventChannel().on('jobTransfer', job => {
      if(!job.locations) {
        job.locations = [];
      }
      this.setData({job: job});
      this.fetchAddress()
    });
    util.getAreasTree(3,false).then(items => {
		this.setData({areas: items});
	  });

  },

  fetchAddress(){
    let that = this;
    core.get({
      url: '/xilujob.company_address/index', loading:false, data: {}, success: ret => {
        let locations  = that.data.job.locations;
        for(let j=0;j<locations.length;j++){
          for(let i=0;i<ret.data.length;i++){
            console.log(locations[j].company_address_id,ret.data[i].id)
              if(locations[j].company_address_id == ret.data[i].id){
                ret.data[i].checked = true;
              }else{
                ret.data[i].checked = false;
              }
          } 
        }
        that.setData({addressList: ret.data});
      }
    });
  },

  bindDistrictChange: function (event) {
    // let selectedDistrict = event.detail.items[0], selectedTown = event.detail.items[1];
    let selectedProvince = event.detail.items[0], selectedCity = event.detail.items[1], selectedDistrict = event.detail.items[2];
    console.log(event)
    this.setData({
      'job.province_id': selectedProvince.id,
      'job.city_id': selectedCity.id,
      'job.district_id': selectedDistrict.id,
      selectedProvince: selectedProvince,
      selectedCity: selectedCity,
      selectedDistrict: selectedDistrict
    });
  },

  bindAddLocation: function() {
    wx.navigateTo({url: '/pages/working_place/working_place', events: {
      'locationAdd': location => {
        this.fetchAddress();
      }
    }});
  },
  bindEditLocation: function (event) {
    let index = event.currentTarget.dataset.index, location = this.data.job.locations[index];
    wx.navigateTo({url: '/pages/working_place/working_place', events: {
      'locationEdit': location => {
        this.setData({'job.locations': this.data.job.locations});
      }
    },success: res => {
      res.eventChannel.emit("locationTransfer", location);
    }});
  },
  bindDelLocation: function (event) {
    wx.showModal({title: '提示', content: '是否确认删除？',
      success: res=>{
        if (res.confirm) {
          let index = event.currentTarget.dataset.index;
          this.data.job.locations.splice(index, 1);
          this.setData({'job.locations': this.data.job.locations});
        }
      }
    });

  },

  bindNextStep: function (event) {

    let addressList = this.data.addressList;
    let locations = [];
    for(let i=0;i<addressList.length;i++){
      if(addressList[i].checked){
        locations.push({
          company_address_id: addressList[i].id,
          province_id: addressList[i].province_id,
          city_id: addressList[i].city_id,
          district_id: addressList[i].district_id,
          address_name: addressList[i].address_name,
          address: addressList[i].address,
          house_number: addressList[i].house_number,
          lat: addressList[i].lat,
          lng: addressList[i].lng,
        })
      }
    }
    let job = this.data.job;
    job.locations = locations; 

    let validator = new WeValidator({
      rules: {
        district_id: {required:true},
        locations: {required:true},
      },
      messages: {
        district_id: {required:'请选择发布区域'},
        locations: {required:'至少添加一个工作地点'},
      }
    });
    if(!validator.checkData(job)) {
      return;
    }
    console.log(this.data.job)
    wx.navigateTo({url: '/pages/post7/post7', success: res => {
      res.eventChannel.emit("jobTransfer", this.data.job);
    }});
  },
  //删除地址
  bindDel: function(event){
	let page = this;
    let index = event.currentTarget.dataset.index;
	let address = this.data.addressList[index];
	wx.showModal({
	  title: '提示',
	  content: '此地址若有关联使用，则无法删除',
	  complete: (res) => {
		if (res.confirm) {
			core.post({
				url: '/xilujob.company_address/del',
				loading: true,
				data: {id: address.id},
				success: ret => {
					page.fetchAddress();
				}
			  });
		}
	  }
	})
    
  }

});
